package com.copd.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordUtil {
    private static final Logger logger = LoggerFactory.getLogger(PasswordUtil.class);

    /**
     * 使用SHA-256对密码进行加密
     * @param password 原始密码
     * @return 加密后的密码
     */
    public static String encrypt(String password) {
        try {
            // 创建SHA-256摘要实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            
            // 使用UTF-8编码
            byte[] hash = digest.digest(password.getBytes("UTF-8"));
            
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            
            logger.debug("Password encryption - Original length: {}", password.length());
            logger.debug("Password encryption - Final hash length: {}", hexString.length());
            logger.debug("Password encryption - Final hash: {}", hexString.toString());
            
            return hexString.toString();
        } catch (Exception e) {
            logger.error("Error encrypting password", e);
            throw new RuntimeException("密码加密失败", e);
        }
    }

    /**
     * 验证密码
     * @param rawPassword 前端传来的SHA-256加密密码
     * @param storedPassword 数据库中存储的密码
     * @return 是否匹配
     */
    public static boolean matches(String rawPassword, String storedPassword) {
        logger.debug("Password verification - Raw password length: {}", rawPassword != null ? rawPassword.length() : 0);
        logger.debug("Password verification - Stored password length: {}", storedPassword != null ? storedPassword.length() : 0);
        logger.debug("Password verification - Raw password: {}", rawPassword);
        logger.debug("Password verification - Stored password: {}", storedPassword);
        
        try {
            if (rawPassword == null || storedPassword == null) {
                logger.debug("Password verification failed - null password");
                return false;
            }
            
            // 检查长度（SHA-256 哈希值应该是 64 个字符）
            if (rawPassword.length() != 64 || storedPassword.length() != 64) {
                logger.debug("Password verification failed - invalid hash length");
                return false;
            }
            
            // 直接比较SHA-256加密后的密码
            boolean matches = rawPassword.equalsIgnoreCase(storedPassword);
            logger.debug("Password verification result: {}", matches);
            
            if (!matches) {
                logger.debug("Password verification failed - passwords do not match");
            }
            
            return matches;
        } catch (Exception e) {
            logger.error("Error verifying password", e);
            return false;
        }
    }
} 